package com.world.rickcloudendpoint.service.net.websocket;

import com.alibaba.fastjson.JSON;
import com.world.rickcloudendpoint.common.constant.GlobalConstants;
import com.world.rickcloudendpoint.common.enums.Cmd;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.net.URLDecoder;
import java.util.Collections;

/**
 * @description: web socket 连接通道服务端 解码  处理器
 * @author: jlsong
 * @date: 2021/12/08 21:29:01
 * @version: 1.0
 */
@Log4j2
@Component
@ChannelHandler.Sharable
public class SocketChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 缓存集合
     */
    final TopicSubscribeManager manager;

    public SocketChannelHandler(TopicSubscribeManager manager) {
        this.manager = manager;
    }


    /**
     * 客戶端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info(String.format("%s通道连接已打开，ID->%s......", GlobalConstants.WEB_SOCKET_LOG_ID, channel.id().asLongText()));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info(String.format("%s 通道连接已断开，ID->%s，主题->%s, 用戶ID->%s......", GlobalConstants.WEB_SOCKET_LOG_ID, channel.id().asLongText(), manager.getTopic(channel), manager.getUid(channel)));

        manager.unRegister(channel);
        channel.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            Channel channel = ctx.channel();
            WebSocketServerProtocolHandler.HandshakeComplete handshakeComplete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
            String requestUri = handshakeComplete.requestUri();
            requestUri = URLDecoder.decode(requestUri, "UTF-8");
            log.info(String.format("%s 握手成功[handshake complete]，ID->%s，URI->%s", GlobalConstants.WEB_SOCKET_LOG_ID, channel.id().asLongText(), requestUri));
            // 检验是否路径带/topic，如果带的话:
            // /topic/Aaa/uid/1?-->订阅Aaa主题
            SessionInfo sessionInfo = manager.getSessionFromRequestRui(requestUri, channel);
            if (sessionInfo != null) {
                manager.register(sessionInfo.getTopic(), sessionInfo.getUid(), channel);
                manager.send(channel, Cmd.Title_Register, Cmd.Title_Register.getDesc());
            } else {
                log.debug("{}未传递订阅主题和用户id，连接将断开.....", GlobalConstants.WEB_SOCKET_LOG_ID );
                manager.send(channel, Cmd.Title_VALID_PARAM, Cmd.Title_VALID_PARAM.getDesc());
                channel.disconnect();
                ctx.close();
            }
        }
        super.userEventTriggered(ctx, evt);
    }


    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        log.error(String.format("%s 连接出現异常，ID->%s，主题->%s，用戶ID->%s，异常->%s......", GlobalConstants.WEB_SOCKET_LOG_ID, channel.id().asLongText(), manager.getTopic(channel), manager.getUid(channel), cause.getMessage()), cause);
        manager.unRegister(channel);
        ctx.close();
    }

    /**
     * 客戶端发消息会触发
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        try {
            log.info("channelRead0: 接收到客戶端發送的消息：{} ", msg.text());

            ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(Collections.singletonMap("cmd", "100"))));
        } catch (Exception e) {
            log.error(String.format("%s 消息异常：%s", GlobalConstants.WEB_SOCKET_LOG_ID, e.getMessage(), e));
        }
    }

}
